package com.es.elasticsearch.controller;

import com.es.elasticsearch.dao.es.EsBlogDao;
import com.es.elasticsearch.dao.mysql.BlogDao;
import com.es.elasticsearch.model.es.EsBlog;
import com.es.elasticsearch.model.mysql.MysqlBolg;
import lombok.Data;


import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * @Auther: Administrator
 * @Date: 2019-12-31 13:37
 * @Description:
 */
@RestController
public class DataController {


    @Autowired
    EsBlogDao esBlogDao;

    @Autowired
    BlogDao blogDao;

    @GetMapping("/blogs")
    public Object blog(){
        List<MysqlBolg> mysqlBolgs = blogDao.queryAll();
        return mysqlBolgs;
    }

    @PostMapping("/search")
    public Object search(@RequestBody Param param){
        HashMap<String,Object> map = new HashMap<>();
        StopWatch stop = new StopWatch("test");
        stop.start();
        if (param.getType().equals("mysql")){
            List<MysqlBolg> mysqlBolgs = blogDao.queryBlogs(param.getKeyword());
            map.put("list",mysqlBolgs);
        }else{
            /*GET /blog/_search
            {
              "query": {
                "bool": {
                  "should": [
                    {
                      "match_phrase": {
                        "title": "卧槽"
                      }
                    },
                    {
                       "match_phrase": {
                        "author": "吴"
                      }
                    }
                  ]
                }
              }

            }*/
            BoolQueryBuilder builder = QueryBuilders.boolQuery();
            builder.should(QueryBuilders.matchPhraseQuery("title",param.getKeyword()));
            builder.should(QueryBuilders.matchPhraseQuery("content",param.getKeyword()));
            System.out.println(builder.toString());
            Page<EsBlog> search = (Page<EsBlog>)esBlogDao.search(builder);
            List<EsBlog> content = search.getContent();
            map.put("list",content);
        }
        stop.stop();
        map.put("duration",stop.getTotalTimeMillis());
        return map;
    }

    @Data
    public static class Param{

        private String type;

        private String keyword;
    }
}
